#!/usr/bin/env python3
"""
Python MCP 客户端
用于与 Playwright MCP 服务器通信
"""

import asyncio
import aiohttp
import json
import logging
from typing import Dict, Any, Optional
from datetime import datetime

class PlaywrightMCPClient:
    def __init__(self, server_url: str = "http://localhost:3000"):
        self.server_url = server_url
        self.session = None
        self.logger = logging.getLogger(__name__)
        
    async def __aenter__(self):
        self.session = aiohttp.ClientSession()
        return self
    
    async def __aexit__(self, exc_type, exc_val, exc_tb):
        if self.session:
            await self.session.close()
    
    async def health_check(self) -> bool:
        """检查服务器健康状态"""
        try:
            async with self.session.get(f"{self.server_url}/health") as resp:
                if resp.status == 200:
                    data = await resp.json()
                    self.logger.info(f"✅ 服务器健康: {data}")
                    return True
                else:
                    self.logger.error(f"❌ 服务器不健康: {resp.status}")
                    return False
        except Exception as e:
            self.logger.error(f"❌ 健康检查失败: {e}")
            return False
    
    async def send_mcp_message(self, message: Dict[str, Any]) -> Dict[str, Any]:
        """发送 MCP 消息"""
        try:
            # 构造 MCP 消息格式
            mcp_message = {
                "jsonrpc": "2.0",
                "id": datetime.now().timestamp(),
                "method": message.get("method"),
                "params": message.get("params", {})
            }
            
            # 发送到 MCP 端点
            async with self.session.post(
                f"{self.server_url}/messages",
                json=mcp_message,
                headers={"Content-Type": "application/json"}
            ) as resp:
                
                if resp.status == 200:
                    result = await resp.json()
                    self.logger.info(f"✅ MCP 消息发送成功: {result}")
                    return result
                else:
                    error_text = await resp.text()
                    self.logger.error(f"❌ MCP 消息发送失败: {resp.status} - {error_text}")
                    return {"error": f"HTTP {resp.status}: {error_text}"}
                    
        except Exception as e:
            self.logger.error(f"❌ MCP 消息发送异常: {e}")
            return {"error": str(e)}
    
    async def navigate(self, url: str) -> Dict[str, Any]:
        """导航到指定URL"""
        return await self.send_mcp_message({
            "method": "browser_navigate",
            "params": {"url": url}
        })
    
    async def click(self, element: str, ref: Optional[str] = None) -> Dict[str, Any]:
        """点击元素"""
        params = {"element": element}
        if ref:
            params["ref"] = ref
        
        return await self.send_mcp_message({
            "method": "browser_click", 
            "params": params
        })
    
    async def type_text(self, element: str, text: str, ref: Optional[str] = None) -> Dict[str, Any]:
        """输入文本"""
        params = {"element": element, "text": text}
        if ref:
            params["ref"] = ref
            
        return await self.send_mcp_message({
            "method": "browser_type",
            "params": params
        })
    
    async def upload_file(self, paths: list) -> Dict[str, Any]:
        """上传文件"""
        return await self.send_mcp_message({
            "method": "browser_file_upload",
            "params": {"paths": paths}
        })
    
    async def take_snapshot(self) -> Dict[str, Any]:
        """获取页面快照"""
        return await self.send_mcp_message({
            "method": "browser_snapshot",
            "params": {"random_string": "snapshot"}
        })
    
    async def wait_for(self, time: Optional[int] = None, text: Optional[str] = None) -> Dict[str, Any]:
        """等待"""
        params = {}
        if time:
            params["time"] = time
        if text:
            params["text"] = text
            
        return await self.send_mcp_message({
            "method": "browser_wait_for",
            "params": params
        })

class XiaohongshuPublisher:
    """小红书发布器"""
    
    def __init__(self, mcp_client: PlaywrightMCPClient):
        self.client = mcp_client
        self.logger = logging.getLogger(__name__)
    
    def generate_daily_content(self):
        """生成每日内容"""
        date_str = datetime.now().strftime("%Y年%m月%d日")
        day_of_week = datetime.now().weekday()
        
        weekly_themes = {
            0: "新周开始，满怀希望！",
            1: "坚持努力，永不放弃！", 
            2: "中周加油，继续前行！",
            3: "即将过半，再接再厉！",
            4: "周末将至，完美收官！",
            5: "周末快乐，享受生活！",
            6: "美好周日，充电时光！"
        }
        
        content = f"""📅 {date_str} 每日分享

{weekly_themes[day_of_week]}

✨ 今天想和大家分享一些生活中的美好瞬间～

生活就像一本书，每一天都是新的一页。让我们用心去感受，用爱去生活，在平凡中发现不平凡的美好！

愿每个人都能在忙碌的生活中，找到属于自己的小确幸 🌟

#每日分享 #生活感悟 #正能量 #美好生活"""
        
        return {
            "title": f"📅 {date_str} 生活分享",
            "content": content
        }
    
    async def publish_daily_content(self, image_path: Optional[str] = None):
        """发布每日内容"""
        try:
            # 1. 检查服务器健康状态
            if not await self.client.health_check():
                raise Exception("MCP 服务器不可用")
            
            # 2. 导航到小红书创作页面
            self.logger.info("🌐 导航到小红书创作页面...")
            result = await self.client.navigate("https://creator.xiaohongshu.com")
            if "error" in result:
                raise Exception(f"导航失败: {result['error']}")
            
            # 等待页面加载
            await self.client.wait_for(time=3)
            
            # 3. 进入发布页面
            self.logger.info("📝 进入发布页面...")
            result = await self.client.navigate("https://creator.xiaohongshu.com/publish/publish")
            if "error" in result:
                raise Exception(f"进入发布页面失败: {result['error']}")
            
            await self.client.wait_for(time=3)
            
            # 4. 点击图文发布
            self.logger.info("🖼️ 选择图文发布...")
            result = await self.client.click("发布图文笔记")
            if "error" in result:
                # 尝试备用选择器
                result = await self.client.click("上传图文")
            
            await self.client.wait_for(time=2)
            
            # 5. 上传图片（如果提供）
            if image_path:
                self.logger.info(f"📷 上传图片: {image_path}")
                result = await self.client.upload_file([image_path])
                if "error" in result:
                    self.logger.warning(f"图片上传失败: {result['error']}")
                else:
                    await self.client.wait_for(time=3)  # 等待上传完成
            
            # 6. 生成并填入内容
            content_data = self.generate_daily_content()
            
            # 填写标题
            self.logger.info("✏️ 填写标题...")
            result = await self.client.type_text("标题输入框", content_data["title"])
            if "error" in result:
                # 尝试备用选择器
                result = await self.client.type_text("填写标题会有更多赞哦～", content_data["title"])
            
            await self.client.wait_for(time=1)
            
            # 填写正文
            self.logger.info("📝 填写正文...")
            result = await self.client.type_text("正文输入框", content_data["content"])
            if "error" in result:
                # 尝试备用选择器
                result = await self.client.type_text("输入正文描述", content_data["content"])
            
            await self.client.wait_for(time=2)
            
            # 7. 发布
            self.logger.info("🚀 发布内容...")
            result = await self.client.click("发布按钮")
            if "error" in result:
                result = await self.client.click("发布")
            
            if "error" in result:
                raise Exception(f"发布失败: {result['error']}")
            
            # 8. 等待发布完成
            await self.client.wait_for(time=5)
            
            # 9. 检查发布结果
            snapshot = await self.client.take_snapshot()
            
            self.logger.info("🎉 发布流程完成！")
            return True
            
        except Exception as e:
            self.logger.error(f"❌ 发布失败: {e}")
            return False

async def main():
    """主函数"""
    logging.basicConfig(
        level=logging.INFO,
        format='%(asctime)s - %(levelname)s - %(message)s'
    )
    
    async with PlaywrightMCPClient() as client:
        publisher = XiaohongshuPublisher(client)
        
        # 执行发布
        success = await publisher.publish_daily_content(
            image_path="/Users/samciu/Sites/cgb-work/playwright-mcp-survey/python-playwright-xhs/sample/background.jpg"
        )
        
        if success:
            print("✅ 每日发布任务完成！")
        else:
            print("❌ 发布任务失败")

if __name__ == "__main__":
    asyncio.run(main())
